/* 
 * Copyright (C) 2014 Krzysztof Troska <elleander86 at gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package anidbjclient;

import com.sun.mail.auth.MD4;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 *
 * @author Krzysztof Troska <elleander86 at gmail.com>
 */
public class Ed2kHash {

    /**
     * Size of ed2k Hash chunks
     */
    private final static int CHUNK_SIZE = 9728000;
    /**
     * Hear we will store ed2kHash
     */
    private byte[] ed2kHash = new byte[0];

    /**
     * Array of basic char helpful with converting ed2k hash in bytes to ed2k
     * Hash in ASCII signs
     */
    private final static char[] HEX = "0123456789abcdef".toCharArray();
    /**
     * File we will be working with
     */
    private final File episode;
    /**
     * Is ed2kHash counted?
     */
    private boolean counted = false;

    /**
     * Creates object of Ed2kHash is getting ready to count hash
     *
     * @param file
     */
    public Ed2kHash(File file) {
        this.episode = file;
    }

    /**
     * Counts ed2k Hash
     * @throws java.io.IOException if we can't read or file don't exist.
     */
    public void count() throws IOException {
        try (BufferedInputStream bs = new BufferedInputStream(new FileInputStream(episode))) {
            MD4 md4 = new MD4();
            int bytes;
            byte[] stream = new byte[CHUNK_SIZE];
            while (true) {
                bytes = bs.read(stream);
                if (bytes == CHUNK_SIZE) {
                    ed2kHash = addByteArrays(ed2kHash, md4.digest(stream));
                } else if (bytes <= 0) {
                    break;
                } else {
                    stream = Arrays.copyOf(stream, bytes);
                    ed2kHash = addByteArrays(ed2kHash, md4.digest(stream));
                    break;
                }
            }
            ed2kHash = md4.digest(ed2kHash);
            counted = true;
        }
    }

    /**
     * Adds array b to the end of array a.
     *
     * @param a first array
     * @param b second array
     * @return array a + b
     */
    private byte[] addByteArrays(byte[] a, byte[] b) {
        byte[] result = new byte[a.length + b.length];
        System.arraycopy(a, 0, result, 0, a.length);
        System.arraycopy(b, 0, result, a.length, b.length);
        return result;
    }

    /**
     * Returns full ed2k Hash with file name etc.
     *
     * @return String full ed2k Hash
     * @throws java.io.IOException when file don't exist or can't read from it
     */
    public String getfullHash() throws IOException {
        final String SEPARATOR = "|";
        StringBuilder sb = new StringBuilder();
        sb.append("ed2k://"); //open
        sb.append(SEPARATOR);
        sb.append("file");//we work only on files
        sb.append(SEPARATOR);
        sb.append(episode.getName().replace(" ", "_")); // file name change " " to "_"
        sb.append(SEPARATOR);
        sb.append(episode.length()); //file length (size)
        sb.append(SEPARATOR);
        sb.append(this.getHash()); //ed2k hash
        sb.append(SEPARATOR);
        sb.append("/"); //always at the end "/"
        return sb.toString();
    }

    /**
     * Writes out ready ed2k Hash (only hash)
     *
     * @return String with ed2k Hash
     * @throws java.io.IOException when file don't exist or can't read from it
     */
    public String getHash() throws IOException {
        if (!counted) {
            count();
        }
        StringBuilder sb = new StringBuilder(ed2kHash.length * 2);
        int b;
        for (int i = 0; i < ed2kHash.length; i++) {
            b = ed2kHash[i] & 0xFF;
            sb.append(HEX[b >>> 4]);
            sb.append(HEX[b & 0x0F]);
        }
        return sb.toString();
    }
}
